package rpc.register;

import rpc.common.MyURL;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 注册中心
 */
public class MyRemoteRegister {
    private static final String FILE_PATH = "/storage.txt";
    /**
     * URLMap
     */
    private static Map<String, List<MyURL>> urlMap = new HashMap<>();

    /**
     * 注册中心注册
     */
    public static void register(String interfaceName, MyURL myURL) {
        if (urlMap.containsKey(interfaceName)) {
            urlMap.get(interfaceName).add(myURL);
        } else {
            List<MyURL> myURLs = new ArrayList<>();
            myURLs.add(myURL);
            urlMap.put(interfaceName, myURLs);
        }

        saveFile();
    }

    public static List<MyURL> get(String interfaceName) {
        urlMap = getByFile();
        return urlMap.get(interfaceName);
    }

    /**
     * 第三方存储
     */
    private static void saveFile() {
        try {
            //获取文件输出流
            FileOutputStream fileOutputStream = new FileOutputStream(FILE_PATH);
            //获取对象输出流
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
            //写入对象
            objectOutputStream.writeObject(urlMap);
            //关闭对象输出流
            objectOutputStream.close();
            //关闭文件输出流
            fileOutputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 从第三方存储中读取
     */
    private static Map<String, List<MyURL>> getByFile() {
        try {
            //获取文件输入流
            FileInputStream fileInputStream = new FileInputStream(FILE_PATH);
            //获取对象输入流
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            //读取对象
            Object object = objectInputStream.readObject();
            //关闭对象输入流
            objectInputStream.close();
            //关闭文件输入流
            fileInputStream.close();
            return (Map<String, List<MyURL>>) object;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
